package com.study.d018tasks;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

/**
*@description
*@author xtayhame
*date 2020年3月16日
*version
*since v1.0
*/
public class Test1 extends Application{
	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage stage) throws Exception {
		AnchorPane anchorPane = new AnchorPane();

		Button startButton = new Button("开始");
		Button cancelButton = new Button("取消");

		ProgressBar  progressBar = new ProgressBar();
		progressBar.setProgress(0.0);

		HBox hBox = new HBox(15);
		hBox.getChildren().addAll(startButton,cancelButton, progressBar);

		AnchorPane.setTopAnchor(hBox, 30.0);
		AnchorPane.setLeftAnchor(hBox, 30.0);

		anchorPane.getChildren().add(hBox);
		stage.setScene(new Scene(anchorPane, 500, 400));
		stage.show();

		Task task = new MyTask();
		Thread thread = new Thread(task);


		startButton.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent event) {
				thread.start();
			}
		});

		task.progressProperty().addListener(new ChangeListener<Number>() {
			@Override
			public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
				System.out.println("progressProperty="+newValue.doubleValue());
				progressBar.setProgress(newValue.doubleValue());
			}
		});

	}

	class MyTask extends Task<Integer> {
		Integer progress= 1;
		@Override
		protected Integer call() throws Exception {
			for(int i=1;i<100000;i++){
				progress= progress + i;
				Thread.sleep(1000);

				//System.out.println("progress="+progress);
				this.updateProgress(progress, 100);
				this.updateValue(progress/100);

				if((progress/100) >=1){
					System.out.println("   跳出 " + progress + "      progress/100 = " + progress/100);
					break;
				}
			}
			System.out.println("测试一下啦");
			return progress;
		}


	}


}
